import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/model/regions.dart';

class SelectRegionsPage extends StatefulWidget {
  List<Regions> regions;
  int type;
  int level;
  SelectRegionsPage({
    this.regions,
    this.type = 1,
    this.level = 0,
  });
  @override
  State<StatefulWidget> createState() =>
      SelectRegionsPageState(regions: regions, type: type, level: level);
}

class SelectRegionsPageState extends State<SelectRegionsPage> {
  List<Regions> regions;
  int type;
  int level;
  Map<String, Object> selectRegions = Map();

  SelectRegionsPageState({
    this.regions,
    this.type,
    this.level,
  });

  @override
  void initState() {
    super.initState();
    if (regions == null) _getRegions();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: _createAppBar(),
        body: ListView.builder(
          itemCount: regions != null ? regions.length : 0,
          itemBuilder: (context, index) => GestureDetector(
                onTap: () {
                  if (regions[index].childs == null ||
                      this.level > 0 && this.type >= this.level) {
                    selectRegions[type.toString()] = regions[index].toJson();
                    Navigator.of(context).pop(selectRegions);
                    return;
                  }
                  if (regions[index].childs != null) {
                    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                      return SelectRegionsPage(
                        regions: regions[index].childs,
                        type: (type + 1),
                        level: level,
                      );
                    })).then((value) {
                      selectRegions = value;
                      selectRegions[type.toString()] = regions[index].toJson();
                      Navigator.of(context).pop(selectRegions);
                    });
                  }
                },
                child: Container(
                  color: Colors.white,
                  margin: const EdgeInsets.only(bottom: 1.0),
                  child: ListTile(
                    title: Text(regions[index].value),
                  ),
                ),
              ),
        ),
      );

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("选择地区"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  _getRegions() {
    NetUtil.get(
      context,
      Api.regions,
      (data, message) {
        if (!mounted) return;
        setState(() {
          if (data != null) {
            regions = (data as List)
                ?.map((e) => e == null ? null : Regions.fromJson(e))
                ?.toList();
          }
        });
      },
    );
  }
}
